package com.miaomiao.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.miaomiao.common.RedisPrefix;
import com.miaomiao.common.Result;
import com.miaomiao.domain.system.*;
import com.miaomiao.mapper.system.UserRoleMapper;
import com.miaomiao.service.system.RoleService;
import com.miaomiao.service.system.UserService;
import com.miaomiao.utils.RedisCache;
import com.miaomiao.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
@CrossOrigin
@Api(tags = "用户信息管理")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RedisCache redisCache;

    @GetMapping
    @PreAuthorize("@ss.hasPermis('system:user')")
    @ApiOperation("获取用户信息列表")
    public Result getPage(@RequestParam int currentPage, int pageSize,String filterName,String state){
        return userService.getPage(currentPage,pageSize,filterName,state);
    }

    @GetMapping("/{userId}")
    @PreAuthorize("@ss.hasPermis('system:user')")
    @ApiOperation("根据userId查询用户信息")
    public Result getUserByUserId(@PathVariable Long userId){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserId,userId);
        User user = userService.getOne(queryWrapper);
        List<Role> userRoles = roleService.getUserRoles(userId);
        return Result.success(new UserVo(user,userRoles));
    }

    @GetMapping("/info")
    @ApiOperation("获取当前登录用户信息")
    public Result getUserInfo(){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserId, SecurityUtils.getUserId());
        User user = userService.getOne(queryWrapper);
        return Result.success(user);
    }

    @PostMapping
    @PreAuthorize("@ss.hasPermis('system:user')")
    @Transactional
    @ApiOperation("注册添加用户")
    public Result addUser(@RequestBody User user){
        boolean save;
        try {
            save = userService.addUser(user);
            // 添加用户角色
            Long roleId = roleService.getRoleIdByRoleKeyLong("register");
            List<UserRole> userRoleList = new ArrayList<>();
            userRoleList.add(new UserRole(user.getUserId(),roleId));
            userRoleMapper.batchUserRole(userRoleList);
        } catch (RuntimeException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("新增失败");
        }
        if(save){
            return Result.success("新增成功");
        }else{
            return Result.error("新增失败");
        }
    }

    @PostMapping("/userRole")
    @PreAuthorize("@ss.hasPermis('system:user')")
    @Transactional
    @ApiOperation("注册添加用户并分配用户角色")
    public Result addUserAndRoles(@RequestBody UserRoleIds userRoleIds){
        List<UserRole> userRoles = userRoleIds.getUserRoles();
        boolean save;
        try {
            User user = userRoleIds.getUser();
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            save = userService.save(user);
            for (UserRole userRole : userRoles) {
                userRole.setUserId(user.getUserId());
            }
            save = save && userRoleMapper.batchUserRole(userRoles) > 0;
        } catch (RuntimeException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("新增失败");
        }
        if(save){
            redisCache.deleteObject(RedisPrefix.ROUTERS_PRE + SecurityUtils.getUserId());
            return Result.success("新增成功");
        }else{
            return Result.error("新增失败");
        }
    }

    @PutMapping("/userRole")
    @PreAuthorize("@ss.hasPermis('system:user')")
    @Transactional
    @ApiOperation("更新用户并分配用户角色")
    public Result updateUserAndRoles(@RequestBody UserRoleIds userRoleIds){
        List<UserRole> userRoles = userRoleIds.getUserRoles();
        boolean update;
        try {
            User user = userRoleIds.getUser();
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(User::getUserId,user.getUserId());

            if(!Objects.isNull(user.getPassword())) {
                user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            }
            update = userRoleMapper.deleteUserRoleByUserId(user.getUserId()) > 0
                    && userRoleMapper.batchUserRole(userRoles) > 0;
            user.setUserName(null);
            user.setUserId(null);
            update = update && userService.update(user, queryWrapper);
        } catch (RuntimeException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("修改失败");
        }
        if(update){
            redisCache.deleteObject(RedisPrefix.ROUTERS_PRE + SecurityUtils.getUserId());
            return Result.success("修改成功");
        }else{
            return Result.error("修改失败");
        }
    }

    @PutMapping
    @PreAuthorize("@ss.hasPermis('system:user')")
    @ApiOperation("更新用户信息")
    public Result updateUser(@RequestBody User user){
        boolean update;
        try {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(User::getUserId,user.getUserId());
            user.setUserName(null);
            if(!Objects.isNull(user.getPassword())) {
                user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            }
            update = userService.update(user, queryWrapper);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
        if(update){
            return Result.success("修改成功");
        }else{
            return Result.error("修改失败");
        }
    }

    @DeleteMapping("/{Ids}")
    @PreAuthorize("@ss.hasPermis('system:user')")
    @ApiOperation("删除用户")
    public Result deleteUser(@PathVariable List<Long> Ids){
        int index = Ids.indexOf(1L);
        if(index != -1){
            Ids.remove(index);
        }
        boolean remove = userService.removeByIds(Ids);
        if(remove){
            if(index != -1){
                return Result.error("admin用户不能删除！");
            }else{
                return Result.success("删除成功");
            }
        }else{
            if(index != -1){
                return Result.error("admin用户不能删除！");
            }else{
                return Result.error("删除失败");
            }
        }
    }

    @PostMapping("/change")
    @ApiOperation("修改密码")
    public Result resetPassword(@RequestBody ChangePwdBody changePwdBody){
        return userService.changePassword(changePwdBody);
    }
}
